package com.example.demo.service;

import com.example.demo.mapper.AuctionMapper;
import com.example.demo.mapper.ReceivingAddressMapper;
import com.example.demo.model.*;
import com.example.demo.config.AjaxResult;
import com.example.demo.vo.AuctionVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class AuctionService {
    
    @Autowired
    private AuctionMapper auctionMapper;
    
    @Autowired
    private ChatService chatService;
    
    @Autowired
    private ReceivingAddressMapper receivingAddressMapper;
    
    @Autowired
    private OrderService orderService;
    
    @Autowired
    private SellerProductService sellerProductService;
    
    public List<AuctionVO> getAuctionList() {
        return auctionMapper.selectList();
    }
    
    public AuctionInfo getAuctionById(Long id) {
        return auctionMapper.selectById(id);
    }
    
    @Transactional
    public AjaxResult placeBid(Long auctionId, Long userId, BigDecimal bidPrice) {
        AuctionInfo auction = auctionMapper.selectById(auctionId);
        if (auction == null) {
            return AjaxResult.fail("拍卖不存在");
        }
        
        // 验证是否为卖家
        if (userId.equals(Long.valueOf(auction.getSellerId()))) {
            return AjaxResult.fail("不能参与自己的拍卖");
        }
        
        if (auction.getStatus() != 1) {
            return AjaxResult.fail("商品不处于拍卖状态");
        }
        
        if (bidPrice.compareTo(auction.getCurrentPrice().add(auction.getMinIncrement())) < 0) {
            return AjaxResult.fail("出价必须高于当前价格加最小加价");
        }
        
        // 创建竞价记录
        AuctionRecord record = new AuctionRecord();
        record.setAuctionId(auctionId);
        record.setUserId(userId);
        record.setBidPrice(bidPrice);
        auctionMapper.insertRecord(record);
        
        // 更新当前价格和胜者ID
        auctionMapper.updateCurrentPrice(auctionId, bidPrice);
        auction.setWinnerId(userId);
        auctionMapper.update(auction);
        
        // 获取第一张图片URL
        String firstImage = "";
        try {
            String[] images = auction.getProductImage().replace("[", "").replace("]", "").split(",");
            if (images.length > 0) {
                firstImage = images[0].trim().replace("\"", "");
            }
        } catch (Exception e) {
            log.error("解析商品图片失败", e);
        }
        
        // 构建带图片的消息内容
        String imageLink = String.format("<a href='auction-detail.html?id=%d'><img src='%s' style='width:200px;height:150px;object-fit:cover;border-radius:8px;'/></a>", 
            auctionId, firstImage);
            
        // 发送给买家的消息
        String buyerMessage = String.format("%s<div style='margin-top:8px;'>您在拍卖「%s」中出价 ¥%.2f</div>", 
            imageLink, auction.getProductName(), bidPrice);
        sendBidNotification(userId, buyerMessage);
        
        // 发送给卖家的消息
        String sellerMessage = String.format("%s<div style='margin-top:8px;'>您的拍卖商品「%s」收到新出价 ¥%.2f</div>", 
            imageLink, auction.getProductName(), bidPrice);
        sendBidNotification(Long.valueOf(auction.getSellerId()), sellerMessage);
        
        return AjaxResult.success("出价成功");
    }
    
    // 添加一个工具方法来获取第一张图片
    private String getFirstImage(String imagesJson) {
        try {
            String[] images = imagesJson.replace("[", "").replace("]", "").split(",");
            if (images.length > 0) {
                return images[0].trim().replace("\"", "");
            }
        } catch (Exception e) {
            log.error("解析商品图片失败", e);
        }
        return "";
    }
    
    public List<AuctionRecord> getAuctionRecords(Long auctionId) {
        return auctionMapper.selectRecordsByAuctionId(auctionId);
    }
    
    private void sendBidNotification(Long userId, String message) {
        ChatMessage notification = new ChatMessage();
        notification.setSenderId(7);  // 使用ID 7作为系统消息
        notification.setReceiverId(userId.intValue());
        notification.setContent(message);
        notification.setType("AUCTION_NOTIFICATION");
        notification.setContentType("HTML");  // 设置内容类型为HTML以支持图片链接
        chatService.saveMessage(notification);
    }
    
    @Scheduled(fixedRate = 60000)
    @Transactional
    public void checkAuctionStatus() {
        // 检查需要开始的拍卖
        List<AuctionInfo> startingAuctions = auctionMapper.selectStartingAuctions();
        if (!startingAuctions.isEmpty()) {
            // 批量更新状态
            auctionMapper.updateStartingAuctionsStatus();
            
            // 发送拍卖开始通知
            for (AuctionInfo auction : startingAuctions) {
                try {
                    String firstImage = getFirstImage(auction.getProductImage());
                    String imageLink = String.format("<a href='auction-detail.html?id=%d'><img src='%s' style='width:100%%;height:150px;object-fit:cover;'/></a>", 
                        auction.getId(), firstImage);
                    String message = String.format("%s<div style='font-size:14px;line-height:1.5;'>拍卖「%s」已开始<br><span style='color:#ff4400;font-weight:bold;'>起拍价：¥%.2f</span></div>", 
                        imageLink, auction.getProductName(), auction.getStartPrice());
                    sendBidNotification(Long.valueOf(auction.getSellerId()), message);
                } catch (Exception e) {
                    log.error("发送拍卖开始通知失败：auctionId=" + auction.getId(), e);
                }
            }
        }

        // 检查需要结束的拍卖
        List<AuctionInfo> endingAuctions = auctionMapper.selectEndingAuctions();
        for (AuctionInfo auction : endingAuctions) {
            try {
                // 更新拍卖状态
                auction.setStatus(2); // 已结束
                auctionMapper.update(auction);
                
                // 如果有胜者，创建订单
                if (auction.getWinnerId() != null) {
                    // 准备订单数据
                    OrderInfo orderInfo = new OrderInfo();
                    orderInfo.setOrderNo(String.format("PM%tY%tm%td%tH%tM%tS%03d",
                            new Date(), new Date(), new Date(), new Date(), new Date(), new Date(),
                            (int) (Math.random() * 1000)));
                    orderInfo.setProductId(auction.getProductId().intValue());
                    orderInfo.setSellerId(Integer.parseInt(auction.getSellerId()));
                    orderInfo.setBuyerId(auction.getWinnerId().intValue());
                    orderInfo.setTotalPrice(auction.getCurrentPrice().toPlainString());
                    
                    // 获取买家默认地址
                    Long defaultAddressId = getDefaultAddress(auction.getWinnerId());
                    if (defaultAddressId != null) {
                        orderInfo.setReceivingId(defaultAddressId.intValue());
                        // 创建订单
                        OrderInfo createdOrder = orderService.createOrderWithDetails(orderInfo);
                        if (createdOrder != null) {
                            String firstImage = getFirstImage(auction.getProductImage());
                            String imageLink = String.format("<a href='auction-detail.html?id=%d'><img src='%s' style='width:100%%;height:150px;object-fit:cover;'/></a>", 
                                auction.getId(), firstImage);
                            String message = String.format("%s<div style='font-size:14px;line-height:1.5;'><span style='font-weight:bold;'>恭喜您在拍卖「%s」中胜出！</span><br><span style='color:#ff4400;font-weight:bold;'>成交价：¥%.2f</span><br>订单号：%s</div>", 
                                imageLink, auction.getProductName(), auction.getCurrentPrice(), orderInfo.getOrderNo());
                            sendBidNotification(auction.getWinnerId(), message);
                        } else {
                            log.error("拍卖结束创建订单失败：auctionId={}", auction.getId());
                        }
                    } else {
                        log.error("买家未设置默认收货地址：auctionId={}, winnerId={}", auction.getId(), auction.getWinnerId());
                        String firstImage = getFirstImage(auction.getProductImage());
                        String imageLink = String.format("<a href='auction-detail.html?id=%d'><img src='%s' style='width:100%%;height:150px;object-fit:cover;'/></a>", 
                            auction.getId(), firstImage);
                        String message = String.format("%s<div style='font-size:14px;line-height:1.5;'><span style='font-weight:bold;'>您在拍卖「%s」中胜出！</span><br><span style='color:#ff4400;'>但由于未设置默认收货地址，订单创建失败</span><br>请及时设置地址并联系客服</div>", 
                            imageLink, auction.getProductName());
                        sendBidNotification(auction.getWinnerId(), message);
                    }
                }
                
                // 发送通知给其他参与者
                List<Long> otherBidders = auctionMapper.selectOtherBidders(auction.getId(), auction.getWinnerId());
                for (Long bidderId : otherBidders) {
                    String firstImage = getFirstImage(auction.getProductImage());
                    String imageLink = String.format("<a href='auction-detail.html?id=%d'><img src='%s' style='width:100%%;height:150px;object-fit:cover;'/></a>", 
                        auction.getId(), firstImage);
                    String message = String.format("%s<div style='font-size:14px;line-height:1.5;'>您参与的拍卖「%s」已结束<br><span style='color:#999;'>很遗憾您未能竞得商品</span></div>", 
                        imageLink, auction.getProductName());
                    sendBidNotification(bidderId, message);
                }
            } catch (Exception e) {
                log.error("处理拍卖结束失败：auctionId=" + auction.getId(), e);
            }
        }
    }
    
    @Transactional
    public boolean createAuction(AuctionInfo auction) {
        try {
            // 设置初始状态为0（未开始）
            auction.setStatus(0);
            // 设置当前价格为起拍��
            auction.setCurrentPrice(auction.getStartPrice());
            return auctionMapper.insert(auction) > 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    /**
     * 获取用户默认收货地址ID
     */
    public Long getDefaultAddress(Long userId) {
        ReceivingAddress defaultAddress = receivingAddressMapper.selectDefaultAddress(userId.intValue());
        return defaultAddress != null ? defaultAddress.getId().longValue() : null;
    }
    
    /**
     * 更新拍卖信息
     */
    public boolean update(AuctionInfo auction) {
        return auctionMapper.update(auction) > 0;
    }
    
    @Transactional
    public boolean updateAuction(AuctionInfo auction) {
        // 验证拍卖是否存在且未开始
        AuctionInfo existingAuction = auctionMapper.selectById(auction.getId());
        if (existingAuction == null || existingAuction.getStatus() != 0) {
            return false;
        }
        
        try {
            // 1. 更新拍卖基本信息（auction_info表）
            AuctionInfo auctionUpdate = new AuctionInfo();
            auctionUpdate.setId(auction.getId());
            auctionUpdate.setStartPrice(auction.getStartPrice());
            auctionUpdate.setMinIncrement(auction.getMinIncrement());
            auctionUpdate.setStartTime(auction.getStartTime());
            auctionUpdate.setEndTime(auction.getEndTime());
            
            boolean auctionUpdated = auctionMapper.update(auctionUpdate) > 0;
            
            // 2. 更新商品信息（product表）
            ProductInfo productUpdate = new ProductInfo();
            productUpdate.setId(existingAuction.getProductId().intValue());
            productUpdate.setName(auction.getProductName());
            productUpdate.setDescription(auction.getProductDescription());
            productUpdate.setImages(auction.getProductImage());
            productUpdate.setBrand(auction.getBrand());
            productUpdate.setLocation(auction.getLocation());
            productUpdate.setOriginalPrice(auction.getOriginalPrice());
            productUpdate.setStatus(Integer.valueOf("1")); // 保持商品状态为已上架
            
            boolean productUpdated = sellerProductService.updateProduct(productUpdate);
            
            return auctionUpdated && productUpdated;
        } catch (Exception e) {
            log.error("更新拍卖商品失败", e);
            throw e;
        }
    }
} 